import * as echarts from 'echarts'
//操作svg图元元素
const initChart = function (container, option) {
  if (!option) {
    return;
  }
  $(container).empty()
  var chart = echarts.init(container, "macarons", {
    renderer: 'svg'
  });
  chart.setOption(option);
  return chart
}
console.log("相应元素属性更新变化")
export class SvgElemOpt {

  constructor(id) {
    this.id = id
    this.elem = this.$id(id)
    this.state = null
    this.events = {}
    this.data = this.elem.attr("data")
    this.docType = this.elem.attr("doc-type")
    this.optionsInit = null;
  }

  $id(id) {
    return $(`#${id}`)
  }

  $qclass(sel) {
    return $(sel)
  }

  call(action, args) {
    this.state = args.state
    console.assert(this.events[action] != null, "event [" + action + "] is undefined in class " + this.constructor.name)
    if (this.events[action]) {
      this.events[action](this, args)
    }
  }
  destroy() {
    this.id = null
    this.elem = null
    this.events = null
    this.state = null
  }
}

export class BYQ extends SvgElemOpt {
  constructor(id) {
    super(id)
    this.events["update" + this.constructor.name] = this.changeColor
    this.events["#svg-byqdoc"] = this.httpMethod
    this.events["#svg-ycdoc"] = this.httpMethod

  }

  call(action, args) {
    this.state = args.state
    console.assert(this.events[action] != null, "event [" + action + "] is undefined in class " + this.constructor.name + ",now will automatically created by the system")

    if (this.events[action] == null) {
      this.events[action] = this.httpMethod
    }
    this.events[action](this, args, action)
  }

  changeColor(this_, args) {
    if (this_.elem.attr("close") == "true") {
      return
    }
    if (this_.elem.attr("close")) {
      if (!args.close || args.close == this_.elem.attr("close")) {
        return
      }
    }
    var use = this_.elem.find("use")[0]


    if (use && use.getAttribute("xlink:href")) {
      var url =  this_.getLastCharStart("_",use.getAttribute("xlink:href"));
      var defs = svGShow.allSvgDefs[url]
      if (defs && defs.length > 1) {
        if (args.val == "true" || args.val == "H") { 
          use.setAttribute("xlink:href",(defs.filter(res=>res.reallyuse==='合'))?.[0]?.['id'] ||  defs[0]['id'] );
        } else {
          use.setAttribute("xlink:href", (defs.filter(res=>res.reallyuse==='分'))?.[0]?.['id'] || defs[1]['id'] );
        }
      }

    }

    if (args.hand != null) {
      if (this_.docType == "KG" && this_.elem.attr("title") && this_.elem.attr("title") != args.val) {
        //如果有开关遥信变位，保留现场
        this_.elem.attr("close", "true")
        use.setAttribute("xlink:href", (defs.filter(res=>res.reallyuse==='其它'))?.[0]?.['id'] || defs[2]['id'] );
      }
    }
    this_.elem.attr("title", args.val)
    if (args.set) {
      this_.elem.attr("close", args.val)
    }
  }


  getLastCharStart = (char,str)=>{
    const lastUnderscoreIndex = str.lastIndexOf(char);
    if (lastUnderscoreIndex !== -1 && str.charAt(lastUnderscoreIndex + 1) !== char) {
      var result = str.substr(0, lastUnderscoreIndex);
    }
    return result;
  }

  httpMethod(this_, args, action) {
    var data = {
      code: "sendmsg", data: {}
    }
    data.data[args.opType] = [{ id: this_.id, type: this_.elem.attr("doc-type"), data: this_.elem.attr("data"), action: action, val: args.val, cmdType: args.cmdType, userName: args.userName }]
    svGShow.sendWorkRequest(data)

  }
}

export class SJB extends BYQ {
}

export class LJB extends BYQ {
}



export class DZ extends BYQ {
  constructor(id) {
    super(id)
    this.events["#svg-H"] = this.ykHMethod
    this.events["#svg-F"] = this.ykFMethod
    this.events["#svg-closeyxH"] = this.yxCloseH
    this.events["#svg-closeyxF"] = this.yxCloseF
    this.events["#svg-openyx"] = this.openyx
    this.events["#svg-reveseset"] = this.reveseset
    this.events["ykyz"] = this.ykyz
    this.events["ykzx"] = this.ykzx
    this.events["#svg-closeyk"] = this.closeyk
    this.events["#svg-openyk"] = this.openyk
  }
  yxCloseH(this_, args) {
    this_.changeColor(this_, { val: "true", close: "H" })
    this_.elem.attr("close", "H")
    this_.httpMethod(this_, { opType: "HTTP", val: "H" }, "yxset")
  }
  yxCloseF(this_, args) {
    this_.changeColor(this_, { val: "false", close: "F" })
    this_.elem.attr("close", "F")
    this_.httpMethod(this_, { opType: "HTTP", val: "F" }, "yxset")
  }
  openyx(this_, args) {
    this_.elem.removeAttr("close")
    this_.httpMethod(this_, { opType: "HTTP", val: null }, "yxset")
  }
  ykHMethod(this_, args) {
    var stats = this_.elem.attr("title")
    if (this_.data.startsWith("33:")) {//开关刀闸配置遥信，禁止遥控
      return
    }
    if (stats == "true" || stats == "H") {
      alert("开关已经处于合闸状态,禁止再合")
      return
    }
    svGShow.ykverify.open("#svg-H", this_)
  }
  ykFMethod(this_, args) {
    var stats = this_.elem.attr("title")
    if (this_.data.startsWith("33:")) {//开关刀闸配置遥信，禁止遥控
      return
    }
    if (stats == "false" || stats == "F") {
      alert("开关已经处于分闸状态，禁止再分")
      return
    }
    svGShow.ykverify.open("#svg-F", this_)
  }
  reveseset(this_, args) {
    if (this_.elem.attr("close")) {
      return
    }
    var use = this_.elem.find("use")[0]
    var uselink = use.getAttribute("xlink:href")
    var url =  this_.getLastCharStart("_",use.getAttribute("xlink:href"));
    // var url = use.getAttribute("xlink:href").split("_")[0]
    var defs = svGShow.allSvgDefs[url]
    if (defs && defs.length > 1) {
      if (uselink == defs[0].id) {
        use.setAttribute("xlink:href", defs[1].id);
      } else {
        use.setAttribute("xlink:href", defs[0].id);
      }
    }
  }

  ykcmd(action, args, dialog) {
    this.dialog = dialog
    this.httpMethod(this, { opType: "YK", cmdType: args.cmdType, userName: svGShow.lastName }, action)
  }

  ykyz(this_, args) {
    svGShow.loadingpage.close()
    var message = args.result.data;
    svGShow.msginfo.open(message)
    if (message == "遥控预置成功") {
      this_.dialog.setBtnYzSuccess()
    }

  }
  ykzx(this_, args) {
    svGShow.loadingpage.close()
    var message = args.result.data;
    svGShow.msginfo.open(message)
    this_.dialog.$docDialog.close()
  }
  closeyk(this_, args) {
    this_.elem.attr("ykClose", "true")
  }
  openyk(this_, args) {
    this_.elem.removeAttr("ykClose")
  }
}

export class gzpai extends BYQ {
  constructor(id) {
    super(id)
    this.events["updategzpai"] = this.refreshYx
    this.events["#svg-clearAll"] = this.clearAll
    this.clearColor = "blue"
    this.YxColor = "red"
    this.page = 0
    this.total = 0
    this.pageSize = this.elem.find(".gzpai_g").length
    this.elem.find(".g_but_class").css("cursor", "pointer")
    var this_ = this
    this.butTitle = ["|◁", "◁", "▷", "▷|", "✔"]
    var args = { opType: "HTTP", id: this.elem.attr("id"), docType: this.elem.attr("doc-type"), data: this.elem.attr("data") }
    $("#" + id + "_but_0g").on("click", function () { this_.homePage(this_) })
    $("#" + id + "_but_1g").on("click", function () { this_.lastPage(this_) })
    $("#" + id + "_but_2g").on("click", function () { this_.nextPage(this_) })
    $("#" + id + "_but_3g").on("click", function () { this_.endPage(this_) })
    $("#" + id + "_but_4g").on("click", function () { this_.clearAll(this_, args) })
  }
  /**
   * svg_5_group_1_0_gzpai
   * 发生遥信事件，光字牌变颜色
   * 做前端分页处理
   */
  refreshYx(this_, args) {
    var gzpais = this_.elem.find(".gzpai_g");
    var state = this_.elem.attr("state");
    var stateParse = JSON.parse(decodeURIComponent(escape(atob(state))))
    var fontsize = stateParse.fontSetValue?.fontnumber ?? 12;

    gzpais.hide()
    this_.total = args.size
    if (this_.total <= gzpais.length) {
      this_.elem.find(".g_but_class").hide()
    } else {
      var id = this_.id
      var totalPage = Math.floor((this_.total - 1) / this_.pageSize + 1)

      $("#" + id + "_but_0_text").text("1" + this_.butTitle[0]).css({
        fontSize:'22px',
      })
      $("#" + id + "_but_1_text").text(((this_.page) > 0 ? (this_.page) : "") + this_.butTitle[1]).css({
        fontSize:'22px',
      })
      $("#" + id + "_but_2_text").text(this_.butTitle[2] + ((this_.page + 2) <= totalPage ? (this_.page + 2) : "")).css({
        fontSize:'22px',
      })
      $("#" + id + "_but_3_text").text(this_.butTitle[3] + totalPage).css({
        fontSize:'22px',
      })
      $("#" + id + "_but_4_text").text(this_.butTitle[4] + (this_.page + 1)).css({
        fontSize:'22px',
      })
    }
    Array.from(args.val).forEach((elem, i) => {
      var index = i
      $(gzpais[index]).attr("data", elem.yxId)
      var id = gzpais[index].id;
      $(gzpais[index]).show()
      $("#" + id + "_gzpai_text").text(elem.yxName)
      $("#" + id + "_gzpai_text").css("font-size", fontsize)
      //此处采用遥信信息类型配置的颜色？
      // $("#" + id + "_gzpai").attr("xlink:href", elem.yxVal == "1" ? "#gzpai_1" : "#gzpai_3");
      if (elem.status == "1") {
        $("#" + id + "_gzpai").attr("xlink:href","#gzpai_1");
        $("#" + id + "_gzpai_text").css("color", "yellow")
        $("#" + id + "_gzpai").attr("style", "animation:twinkle 0.5s infinite alternate");
      } else if(elem.status == "2"){
        $("#" + id + "_gzpai").attr("xlink:href","#gzpai_2");
        $("#" + id + "_gzpai_text").css("color", "black")
        $("#" + id + "_gzpai").attr("style", "animation:none");

      }else{
        //正常状态
        $("#" + id + "_gzpai").attr("xlink:href","#gzpai_3");
        $("#" + id + "_gzpai_text").css("color", "white")
        $("#" + id + "_gzpai").attr("style", "animation:none");
      }
    })
  }
  /**
   *
   * @param {清光字牌} args
   */
  clearAll(this_, args) {
    this_.elem.find("use").attr("xlink:href", "#gzpai_3")
    this_.httpMethod(this_, args, "clearAll")
  }
  pageRequest(this_) {
    var len = svGShow.allSvgObjs["gzpai"].length;
    for (var i = 0; i < len; i++) {
      var gzpai = svGShow.allSvgObjs["gzpai"][i]
      if (gzpai.id == this_.id) {
        gzpai.size = this_.total
        gzpai.page = this_.page
        break;
      }
    }
    var data = {
      code: "sendmsg", data: svGShow.allSvgObjs
    }
    svGShow.sendWorkRequest(data)
  }
  /**
   * 下一页
   * @param {*} this_
   * @returns
   */
  nextPage(this_) {
    if ((this_.page + 1) * this_.pageSize > this_.total) {
      return
    }
    this_.page++
    this_.pageRequest(this_)
  }
  /**
     * 上一页
     * @param {*} this_
     * @returns
     */
  lastPage(this_) {
    if (this_.page == 0) {
      return
    }
    this_.page--
    this_.pageRequest(this_)
  }
  /**
     * 第一页
     * @param {*} this_
     * @returns
     */
  homePage(this_) {
    this_.page = 0
    this_.pageRequest(this_)
  }
  /**
     * 最后一页
     * @param {*} this_
     * @returns
     */
  endPage(this_) {
    this_.page = Math.floor((this_.total + 1) / this.pageSize)
    this_.pageRequest(this_)
  }
}

export class DD extends DZ {
  constructor(id) {
    super(id)
  }
}

export class DLQ extends DZ {
  constructor(id) {
    super(id)
  }
}

export class KG extends DZ {
  constructor(id) {
    super(id)
  }
}

export class DKQ extends DZ {
  constructor(id) {
    super(id)
  }
}

export class DRQ extends DZ {
  constructor(id) {
    super(id)
  }
}

export class FDJ extends DZ {
  constructor(id) {
    super(id)
  }
}

export class BLQ extends DZ {
  constructor(id) {
    super(id)
  }
}

export class QT extends DZ {
  constructor(id) {
    super(id)
    this.events["updateQT"] = this.updateqt
  }

  updateqt(this_, data) {
    var use = this_.elem.find("use")[0]
    var url =  this_.getLastCharStart("_",use.getAttribute("xlink:href"));
    // var url = use.getAttribute("xlink:href").split("_")[0]
    var defs = svGShow.allSvgDefs[url]
    if (defs && defs.length > 1) {
      if(data.val!==null && data.val!="其他" && !isNaN(parseInt(data.val))){
        let arr = defs.map(res=>res.reallyuse);
        if(arr.includes(String(parseInt(data.val)))){
          use.setAttribute("xlink:href", url + "_" + parseInt(data.val));
        }else{
          use.setAttribute("xlink:href", url + "_其他");

        }
        
      }else{
        use.setAttribute("xlink:href", url + "_其他" );
      }
      
     
    }
  }
}

export class GK extends DZ {
  constructor(id) {
    super(id)
  }
}

export class link extends DZ {
  constructor(id) {
    super(id)
  }
}


export class JDDZ extends DZ {
  constructor(id) {
    super(id)
  }
}

export class datatext extends DZ {
  constructor(id) {
    super(id)
    this.events["updatedatatext"] = this.updatedatatext
    this.events["#svg-ycyt"] = this.ytMethod
    this.events["#svg-ycset"] = this.ycset
    this.events["#svg-openyc"] = this.openyc
    this.events["#svg-closeyc"] = this.closeyc
    this.events["ytyz"] = this.ytyz
    this.events["ytzx"] = this.ytzx
    this.events['#svg-todayLine']  =  this.bindopenTodayLine
    this.set = false
  }
  updatedatatext(this_, data) {
    this_.canYt = data.yt
    if (this_.elem.attr("set") || data.val == null) {
      return;
    }
    // 根据小数位格式化数据
    const option = JSON.parse(decodeURIComponent(escape(atob(this_.elem.attr("state")))))
    const Decimalplaces = option.Decimalplaces // 小数位数
    const Displaylength = option.Displaylength // 最大位数
    /**
     *
     * @param number
     * @param maxLength 显示长度
     * @param maxDecimal 小数位数
     * @returns {*}
     */
    function formatNumber(number,maxLength,maxDecimal){
      // 将数字转换为字符串
      let strNumber = number.toString();

      // 分割整数部分和小数部分
      let parts = strNumber.split('.');
      let integerPart = parts[0];
      let decimalPart = parts[1] || '';

      // 根据最大长度截取整数部分
      if (integerPart.length > maxLength) {
        integerPart = integerPart.slice(0, maxLength);
      }

      // 根据最大小数位数截取小数部分
      if (decimalPart.length > maxDecimal) {
        decimalPart = decimalPart.slice(0, maxDecimal);
      }

      // 组合整数部分和小数部分
      let formattedNumber = integerPart;
      if (decimalPart.length > 0) {
        formattedNumber += '.' + decimalPart;
      }
      return formattedNumber;
    }
    this_.elem.find("foreignObject").text(formatNumber(Number(data.val),Number(Displaylength),Number(Decimalplaces)))
    if(data.set == true){
      this_.elem.attr("set",true)
    }
  }


  bindopenTodayLine(svgShow){
    const event=new CustomEvent('openTodayLine',{
      detail:svgShow
    });
    window.parent.dispatchEvent(event)

  }

  ytMethod(this_,data){
    var tx = $("#" + this_.id).find("foreignObject").text()
    if (this_.canYt == "0") {
      return
    }


    svGShow.ytverify.open(tx, this_)
  }

  ytcmd(action, args, dialog) {
    this.dialog = dialog
    this.httpMethod(this, { opType: "YT", cmdType: args.cmdType, val: args.val, userName: svGShow.lastName }, action)
  }

  ytyz(this_, args) {
    this_.dialog.setBtnYzSuccess()
  }
  ytzx(this_, args) {
    svGShow.loadingpage.close()
    svGShow.msginfo.open("执行成功")
    this_.dialog.$docDialog.close()
  }

  ycset(this_, data) {
    svGShow.yczs.open(this_, false);
  }

  closeyc(this_, data) {
    svGShow.yczs.open(this_, true);
  }

  setValue(val, needsave) {
    this.elem.find("foreignObject").text(val)
    if (needsave == false) {
      return
    }
    this.elem.attr("set", true)
    var data = {
      code: "sendmsg", data: {}
    }
    data.data["HTTP"] = [{ id: this.id, type: this.elem.attr("doc-type"), data: this.elem.attr("data"), action: "ycset", val: val }]
    svGShow.sendWorkRequest(data)
  }

  openyc(this_, data) {
    this_.elem.removeAttr("set")
    var data = {
      code: "sendmsg", data: {}
    }
    data.data["HTTP"] = [{ id: this_.id, type: this_.elem.attr("doc-type"), data: this_.elem.attr("data"), action: "ycset" }]
    svGShow.sendWorkRequest(data)
  }
}

export class barry extends BYQ {
  constructor(id) {
    super(id)
    this.events["updatebarry"] = this.changeSOC
  }
  changeSOC(this_, data) {
    if (!data.val) return
    var defsId = "lg_barry_" + this_.id
    var textid = this_.id + "_text"
    $("#" + textid).text(data.val + "%")
    var val = Math.floor(100 - parseFloat(data.val))
    $("#" + defsId).attr("y1", val / 100 + 0.01)
    $("#" + defsId).attr("y2", val / 100)
  }
}

export class echart extends BYQ {
  constructor(id) {
    super(id)
    this.events["initChart"] = this.init
    this.events["updateechart"] = this.updateechart
    this.chart = null
    this.option = {};
    this.data = JSON.parse(decodeURIComponent(escape(atob(this.elem.attr("state")))))
    this.init(this)
  }
  formatter(value, index) {
    if (value == '0:0:0') {
      return "00:00:00";
    } else if (value == '23:59:59') {
      return "23:59:59";
    } else {
      return value;
    }
  }
  init(this_) {
    var foreignObjects = $("#" + this_.id).find(".foreignObject")
    Array.from(foreignObjects).forEach((elem, i) => {
      $(elem).removeAttr("_echarts_instance_")
      if (this_.chart) {
        this_.chart.dispose()
      }
      var data = $(elem).parent().attr("requiredFeatures")
      if (data) {
        this_.option = JSON.parse(decodeURIComponent(escape(atob(data))))
      }
      this_.chart = initChart(document.getElementById(elem.id), this_.option)
      this_.chart.dispatchAction({
        type: 'takeGlobalCursor',
        key: 'dataZoomSelect',
        dataZoomSelectActive: true
      })
    })
  }
  updateechart(this_, data) {

    // if (data.option.initX) {
    //   this_.option.toolbox = {
    //     show: true,
    //     feature: {
    //       dataZoom: {
    //         yAxisIndex: "none"
    //       },
    //       //其他功能性按钮查看官网进行增加，包括（显示数据，下载图片，改为柱状图等）
    //     }
    //   }
    //   this_.option.tooltip = {
    //     show: true,
    //     trigger: 'axis',
    //     axisPointer: {
    //       type: 'cross'
    //     },
    //   }


    //   this_.option.xAxis.axisLabel = {
    //     show: true,
    //     interval: 60 * 60 * 2 - 1,
    //     formatter: this_.formatter,
    //     textStyle: {
    //       color: 'red'
    //     },
    //   },
    //     this_.option.xAxis.data = data.option.xAxisData
    //   Array.from(data.option.seriesData).forEach((val, index) => {
    //     this_.option.series[index].data = val
    //   })
    // } else {
    //   Array.from(this_.option.series).forEach((val, index) => {
    //     this_.option.series[index].data = [];
    //     this_.option.series[index].data.push(data.data.lineSet[index].test)
    //   })
    // }





    let options = JSON.parse(data.data.val);
    if(options){
      if(options.xAxis && options.xAxis.length){
        try{
          options.xAxis[0]['axisLabel']['formatter'] =  (value)=> value?.substring(0, 2);
          options.xAxis[0]['axisLabel']['interval'] =  60;

        }catch(err){

        }
       

      }
    }
    this_.chart.setOption(options)
   
  }
}

export class barechart extends BYQ {
  constructor(id) {
    super(id)
    this.events["initChart"] = this.init
    this.events["updatebarechart"] = this.updatebarechart
    this.chart = null
    this.option = {};
    this.data = JSON.parse(decodeURIComponent(escape(atob(this.elem.attr("state")))))
    this.renderItem = function (params, api) {
      let categoryIndex = api.value(0)
      let start = api.coord([categoryIndex, api.value(1)])
      let end = api.coord([categoryIndex, api.value(2)])
      let width = api.size([0, api.value(2)])[0] * 0.8
      const num = api.value(4) // 每个系列柱子数
      const currentIndex = api.value(3)
      const isOdd = num % 2 === 0
      const midN = isOdd ? num / 2 : (num + 1) / 2
      var rect = ''
      width = width / num
      let rectX = start[0] - width / 2
      const FIXED_WIDTH = 0 // 柱子间距
      // 数据处理，结构为 { itemStyle: { normal: { color: 'lightgreen' } }, name: '2011', value: [0, 0, 150, 2, 5] }
      // 其中value 分为五个维度，分别为{系列项}（从0开始）、y轴起始值(均为0)、实际值、同系列中索引值（从1开始）、同系列数据项总数
      if (num > 1) {
        if (isOdd) {
          if (currentIndex <= midN) {
            // 中位数左侧
            rectX =
              start[0] - width / 2 - width / 2 + (currentIndex - midN) * width - FIXED_WIDTH * (midN + 1 - currentIndex)
          } else {
            // 中位数右侧
            rectX =
              start[0] - width / 2 + width / 2 + (currentIndex - midN - 1) * width + FIXED_WIDTH * (currentIndex - midN)
          }
        } else {
          rectX = start[0] - width / 2 + (currentIndex - midN) * (width + FIXED_WIDTH)
        }
      }
      rect = {
        type: 'rect',
        shape: echarts.graphic.clipRectByRect(
          { x: rectX, y: end[1], width: width, height: start[1] - end[1] },
          {
            x: params.coordSys.x,
            y: params.coordSys.y,
            width: params.coordSys.width,
            height: params.coordSys.height
          }
        ),
        style: api.style()
      }
      return rect
    }
    this.init(this)
  }
  init(this_) {
    var foreignObjects = $("#" + this_.id).find(".foreignObject_bar")
    Array.from(foreignObjects).forEach((elem, i) => {
      $(elem).removeAttr("_echarts_instance_")
      if (this_.chart) {
        this_.chart.dispose()
      }
      var state = $(elem).parent().attr("requiredFeatures")
      if (state) {
        this_.option = JSON.parse(decodeURIComponent(escape(atob(state))))
        this_.option.series[0].renderItem = this_.renderItem
      }
      this_.chart = initChart(document.getElementById(elem.id), this_.option)
    })
  }

  updatebarechart(this_, data) {
    var d = (data.data.barGroupSet)
    var index = 0;
    for (var i = 0; i < d.length; i++) {

      var barSet = d[i].barSet
      for (var j = 0; j < barSet.length; j++) {
        try {
          this_.option.series[0].data[index].value[2] = parseFloat(barSet[j].test)
        } catch (e) {
        }
        index++
      }
    }

    this_.option.xAxis.axisTick = {
      show: true,
      inside: true
    }
    this_.option.series[0]['label']['fontSize']=20;
    delete this_.option.legend.data;
    // console.log(this_.option,"我看下进这里没")
    this_.chart.setOption(this_.option, true)
  }
}


export class piechart extends BYQ {
  constructor(id) {
    super(id)
    this.events["initChart"] = this.init
    this.events["updatepiechart"] = this.updatepiechart
    this.data = JSON.parse(decodeURIComponent(escape(atob(this.elem.attr("state")))))
    this.chart = null
    this.option = {
      title: {
        text: 'Referer of a Website',
        subtext: 'Fake Data',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        textStyle: {
          color: "white"
        }
      },
      series: [
        {
          name: 'Access From',
          type: 'pie',
          radius: '70%',
          data: [
            { value: 1048, name: 'Search Engine' },
            { value: 735, name: 'Direct' },
            { value: 580, name: 'Email' },
            { value: 484, name: 'Union Ads' },
            { value: 300, name: 'Video Ads' }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
        }
      ]
    };
    this.init(this)

  }
  init(this_) {
    var foreignObjects = $("#" + this_.id).find(".foreignObject_pie")
    Array.from(foreignObjects).forEach((elem, i) => {
      $(elem).removeAttr("_echarts_instance_")
      if (this_.chart) {
        this_.chart.dispose()
      }
      this_.chart = initChart(document.getElementById(elem.id), this_.option)
    })
  }
  updatepiechart(this_, data) {
    var seriesData = []
    if (data.option.name) {
      data.option.name.forEach((val, index) => {
        seriesData.push({ name: val, value: data.option.value[index] })
      })
    }
    var option = {
      series: [
        {
          data: seriesData,
        }]
    }
    this_.chart.setOption(option)
  }
}


export class gaugechart extends BYQ {
  constructor(id) {
    super(id)
    this.events["initChart"] = this.init
    this.events["updategaugechart"] = this.updategaugechart
    this.chart = null
    this.option = {
      tooltip: {
        formatter: '{a} <br/>{b} : {c}%'
      },
      series: [
        {
          name: 'Pressure',
          type: 'gauge',
          min: 0,
          max: 180,
          detail: {
            formatter: '{value}'
          },
          data: [
            {
              value: 50,
              name: 'SCORE'
            }
          ]
        }
      ]
    };
    this.init(this)
  }
  init(this_) {
    var foreignObjects = $("#" + this_.id).find(".foreignObject_gauge")
    Array.from(foreignObjects).forEach((elem, i) => {
      $(elem).removeAttr("_echarts_instance_")
      if (this_.chart) {
        this_.chart.dispose()
      }
      this_.chart = initChart(document.getElementById(elem.id), this_.option)
    })
  }
  updategaugechart(this_, data) {
    var option = {
      series: [{
        data: [
          {
            value: data.val,
          }
        ]
      }]
    }
    this_.chart.setOption(option)
  }
}

export const createSvgOpts = (name, id) => {
  try {
    var cls = eval(name)
    var obj = new cls(id)
    return obj
  } catch (e) {
    console.error("class " + name + " is not found")
  }

}

export default createSvgOpts
